package com.example.thread;

import lombok.Setter;

import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author YDF
 * @date 2019/12/31
 */
@Setter
public class Worker implements Runnable {

    private ConcurrentLinkedQueue<Task> taskQueue;
    private ConcurrentHashMap<String, Object> resultMap;

    @Override
    public void run() {
        while (true) {
            Task executeTask = this.taskQueue.poll();
            if (Objects.isNull(executeTask)) {
                break;
            }
            Object result = handle(executeTask);
            resultMap.put(executeTask.getName(), result);
        }
    }

    private Object handle(Task executeTask) {
        Object result = null;
        try {
            System.out.println(Thread.currentThread().getName() + " : " + executeTask.getName() + " : " + executeTask.getPrice());
            TimeUnit.SECONDS.sleep(5);
            result = executeTask.getPrice();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return result;
    }
}
